import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Input, Divider, Image, Toast } from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { Flex } from 'antd';

import styles from './index.module.css'

import { jumpTo } from '../../jump'
import { getVerificationCode, startLogin } from '../../axiosRequest/api2'

//持久化
import { token_cache_key } from '../../cache/cacheKey'
import { setCache } from '../../cache'

function Login() {
    let navigate = useNavigate()
    const [userName, setUserName] = useState('')
    const [userPwd, setUserPwd] = useState('')
    const [eyeVisible, setEyeVisible] = useState(false)
    const [img, setImg] = useState("")
    //验证码的key-回传给后端
    const [key, setKey] = useState("")
    //验证码
    const [captcha, seCaptcha] = useState("")

    //[]空数组相当于componentDidMount
    useEffect(() => {
        getCaptcha()
        //返回的函数相当于unmountComponentAtNode
        return () => {

        }
    }, []);

    function onChangeUserName(val) {
        setUserName(val)
    }

    function onChangeUserPwd(val) {
        setUserPwd(val)
    }

    function onCaptcha(val) {
        seCaptcha(val)
    }

    function clickCaptcha() {
        getCaptcha()
    }

    function getCaptcha() {
        // const obj1 = {
        //     aaa: 'asdasdasd',
        //     bbb: '13248789'
        // }
        const obj1 = new Map();
        getVerificationCode(obj1)
            .then(response => {
                const data = response.data;
                console.log('getcode>', data);
                setImg('data:image/png;base64,' + data.data.imgBase64)
                setKey(data.data.key)
            })
            .catch(error => {
                console.log('getcode-error>', error);
                Toast.show({ icon: 'fail', content: '获取验证码失败' })
                console.log(error);
            });
    }

    function clickLogin() {
        //用replace，替换当前栈顶的记录
        //navigate('/main/home', { replace: true, state: { id: 1 } })
        // const obj1 = {
        //     key: key,
        //     captcha: captcha
        // }
        const obj1 = new Map();
        obj1.set("key", key);
        obj1.set("captcha", captcha);
        startLogin(obj1)
            .then(response => {
                const data = response.data
                console.log('login>', data);
                const code = data.code;
                if (code === 1000) {
                    //保存token
                    setCache(token_cache_key, data.data.token)
                    jumpTo(navigate, '/main/home', true, null)
                } else {
                    //验证码输入错误
                    Toast.show({ icon: 'fail', content: data.des })
                }
            })
            .catch(error => {
                console.log('login-error>', error);
                Toast.show({ icon: 'fail', content: '登录失败' })
            });

        //jumpTo(navigate, '/main/home', true, null)
    }


    return (<Flex style={{ 'height': '80vh' }} justify='center' align='center'>
        <div style={{ 'width': '350px' }}>
            <Input style={{ '--font-size': '18px' }} value={userName} onChange={onChangeUserName} maxLength='10'
                placeholder='请输账号...' clearable />
            <Divider />
            <div className={styles.password}>
                <Input style={{ '--font-size': '18px' }} value={userPwd} onChange={onChangeUserPwd}
                    type={eyeVisible ? 'text' : 'password'} maxLength='10' placeholder='请输密码...' />
                {!eyeVisible ? (<EyeInvisibleOutline style={{ 'width': '20px', 'height': '20px' }}
                    onClick={() => setEyeVisible(true)} />) : (
                    <EyeOutline style={{ 'width': '20px', 'height': '20px' }} onClick={() => setEyeVisible(false)} />)}
            </div>
            <Divider />
            <div className={styles.verification}>
                <Input className={styles.inp_verification} onChange={onCaptcha} style={{ '--font-size': '18px' }} type={'number'} placeholder='请输入验证码...' />
                <Image onClick={clickCaptcha} src={img} width={120} height={60} fit='contain' />
            </div>
            <Divider />
            <Button className={styles.login_button} onClick={clickLogin} block color='primary' size='large'>点击登录</Button>
        </div>
    </Flex>)
}

export default Login;
